package com.tourex.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.tourex.R;
import com.tourex.utils.BaseUtils;
import com.tourex.utils.ImageUtils;

public class MRatingBar extends LinearLayout {

	private static final int DEFAULT_TOTAL = 5;
	private static final int DEFAULT_SPACING = 5;

	private Bitmap starHollow;
	private Bitmap starSolid;

	private int total;
	private int spacing;

	public MRatingBar(Context context) {
		this(context, null);
	}

	public MRatingBar(Context context, AttributeSet attrs) {
		super(context, attrs);

		setOrientation(HORIZONTAL);

		TypedArray ta = context.obtainStyledAttributes(attrs,
				R.styleable.MRatingBar);
		total = ta.getInt(R.styleable.MRatingBar_total, DEFAULT_TOTAL);
		spacing = ta.getInt(R.styleable.MRatingBar_spacing, DEFAULT_SPACING);

		ta.recycle();

	}

	public void setData(final int current) {
		post(new Runnable() {
			@Override
			public void run() {
				int reqHeight = getHeight();
				starHollow = ImageUtils.decodeResource(getResources(),
						R.drawable.ico_star_hollow, reqHeight, reqHeight);
				starSolid = ImageUtils.decodeResource(getResources(),
						R.drawable.ico_star_solid, reqHeight, reqHeight);
				
				removeAllViewsInLayout();

				LinearLayout.LayoutParams LP = new LinearLayout.LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				int margins = BaseUtils.dip(getContext(), spacing);
				LP.setMargins(0, 0, margins, 0);

				for (int i = 0; i < total; i++) {
					ImageView imageView = new ImageView(getContext());
					if (i < current) {
						imageView.setImageBitmap(starSolid);
					} else {
						imageView.setImageBitmap(starHollow);
					}

					imageView.setAdjustViewBounds(true);
					imageView.setLayoutParams(LP);
					addView(imageView);
				}
			}
		});
	}
}
